import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_overlay/flutter_overlay.dart';
import 'package:net/barrage/barrage_input.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:net/http/dao/favorite_dao.dart';
import 'package:net/http/dao/like_dao.dart';
import 'package:net/http/dao/video_detail_dao.dart';
import 'package:net/model/video_detail_mo.dart';
import 'package:net/model/video_model.dart';
import 'package:net/provider/theme_provider.dart';
import 'package:hi_base/log.dart';
import 'package:hi_base/toast.dart';
import 'package:net/widget/appbar.dart';
import 'package:net/widget/expandable_content.dart';
import 'package:net/widget/h_tab.dart';
import 'package:net/widget/navigation_bar.dart';
import 'package:net/widget/video_header.dart';
import 'package:net/widget/video_large_card.dart';
import 'package:net/widget/video_toolbar.dart';
import 'package:net/widget/video_view.dart';
import 'package:provider/provider.dart';
import 'package:hi_barrage/h_barrage.dart';
import 'package:net/widget/barrage_switch.dart';
import 'package:net/utils/hi_constants.dart';

class VideoDetailPage extends StatefulWidget {
  final VideoModel videoModel;

  const VideoDetailPage(this.videoModel);

  @override
  _VideoDetailPageState createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage>
    with TickerProviderStateMixin {
  TabController _controller;
  List tabs = ["简介", "评论288"];
  VideoModel videoModel;
  List<VideoModel> videoList = [];
  VideoDetailMo videoDetailMo;
  // key
  var _barrageKey = GlobalKey<HBarrageState>();
  //
  bool inputShowing;
  @override
  void initState() {
    super.initState();
    _controller = TabController(length: tabs.length, vsync: this);
    videoModel = widget.videoModel;
    // changeStatusBar(
    //   color: Colors.white,
    //   statusStyle: StatusStyle.LIGHT_CONTENT,
    // );
    _loadDetail();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 适配theme
    var themeProvider = context.watch<ThemeProvider>();
    var _bgColor = !themeProvider.isDark() ? Colors.white : Color(0xff30343c);
    var _bgGrey =
        !themeProvider.isDark() ? Colors.grey[100] : Color(0xaa30343c);
    return Scaffold(
      body: Container(
        child: MediaQuery.removePadding(
          removeTop: Platform.isIOS,
          context: context,
          child: videoModel.url != null
              ? Column(
                  children: [
                    HNavigationBar(
                      color: Colors.white,
                      statusStyle: StatusStyle.DARK_CONTENT,
                      height: Platform.isAndroid ? 0 : 46,
                    ),
                    _videoView(),
                    // tab 标题
                    _buildTabNavigation(_bgColor, _bgGrey),
                    // tab内容
                    Flexible(
                        child: TabBarView(
                      controller: _controller,
                      children: [
                        // 简介
                        _buildDetailList(),
                        // 评论
                        Container(
                          child: Text('评论页面正在开发中...'),
                        ),
                        //
                      ],
                    ))
                  ],
                )
              : Container(),
        ),
      ),
    );
  }

// 视频组件
  _videoView() {
    var model = videoModel;
    return VideoView(
      url: model.url,
      cover: model.cover,
      overlayUI: videoAppBar(),
      barrageUI: HBarrage(
        key: _barrageKey,
        vid: model.vid,
        autoPlay: true,
        headers: HiConstans.headers(),
      ),
    );
  }

  // tab标题
  _buildTabNavigation(_bgColor, _bgGrey) {
    //使用Material实现阴影效果
    return Material(
      elevation: 5,
      shadowColor: _bgGrey,
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 20),
        height: 39,
        color: _bgColor,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _tabBar(),
            _buildBarrageBtn(),
          ],
        ),
      ),
    );
  }

  _tabBar() {
    return HTab(
      tabs: tabs.map<Tab>((name) {
        return Tab(
          text: name,
        );
      }).toList(),
      controller: _controller,
    );
  }

  // tab内容
  _buildDetailList() {
    return ListView(
      padding: EdgeInsets.all(0),
      children: [...buildContents(), ..._buildVideoList()],
    );
  }

  buildContents() {
    return [
      // 头部
      VideoHeader(
        owner: videoModel.owner,
      ),
      // 展开-关闭
      HExpandableContent(mo: videoModel),
      //点赞栏
      VideoToolBar(
        detailMo: videoDetailMo,
        videoModel: videoModel,
        onLike: _doLike,
        onUnLike: _onUnLike,
        onFavorite: _onFavorite,
      )
    ];
  }

// 获取数据
  void _loadDetail() async {
    try {
      VideoDetailMo result = await VideoDetailDao.get(widget.videoModel.vid);
      //  hyLog(result, current)
      setState(() {
        videoDetailMo = result;
        //更新旧的数据--之前是传过来的，时间久了数据就会有变化所以需要掉接口进行更新(也可以直接用这个)
        videoModel = result.videoInfo;
        videoList = result.videoList;
      });
    } on NeedAuth catch (e) {
      hyLog(e, StackTrace.current);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      hyLog(e, StackTrace.current);
    }
  }

  // 点赞
  void _doLike() async {
    try {
      var result = await LikeDao.like(videoModel.vid, !videoDetailMo.isLike);
      // print(result);
      if (result['code'] != 0) return;
      videoDetailMo.isLike = !videoDetailMo.isLike;
      if (videoDetailMo.isLike) {
        videoModel.like += 1;
      } else {
        videoModel.like -= 1;
      }
      setState(() {
        videoDetailMo = videoDetailMo;
        videoModel = videoModel;
      });
      showToast(result['msg']);
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print(e);
    }
  }

  // 取消点赞
  void _onUnLike() {}
  // 收藏
  void _onFavorite() async {
    try {
      var result =
          await FavoriteDao.favorite(videoModel.vid, !videoDetailMo.isFavorite);
      // hyLog(result, StackTrace.current);
      if (result['code'] != 0) return;
      videoDetailMo.isFavorite = !videoDetailMo.isFavorite;
      if (videoDetailMo.isFavorite) {
        videoModel.favorite += 1;
      } else {
        videoModel.favorite -= 1;
      }
      setState(() {
        videoDetailMo = videoDetailMo;
        videoModel = videoModel;
      });
      showToast(result['msg']);
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print(e);
    }
  }

  // 相关视频列表页面
  _buildVideoList() {
    return videoList.map((VideoModel mo) => VideoLargeCard(
          videoModel: mo,
        ));
  }

  _buildBarrageBtn() {
    // return InkWell(
    //   onTap: () {
    //     HiOverlay.show(context, child: BarrageInput(
    //       onTabClose: () {
    //         setState(() {
    //           inputShowing = false;
    //         });
    //       },
    //     )).then((value) {
    //       hyLog('..input:$value', StackTrace.current);
    //       // 发送弹幕
    //       _barrageKey.currentState.send(value);
    //     });
    //   },
    //   child: Padding(
    //     padding: EdgeInsets.only(right: 20),
    //     child: Icon(
    //       Icons.live_tv_rounded,
    //       color: Colors.grey,
    //     ),
    //   ),
    // );
    return BarrageSwitch(onShowInput: () {
      HiOverlay.show(context, child: BarrageInput(
        onTabClose: () {
          setState(() {
            inputShowing = false;
          });
        },
      )).then((value) {
        hyLog('..input:$value', StackTrace.current);
        // 发送弹幕
        _barrageKey.currentState.send(value);
      });
    }, onBarrageSwitch: (value) {
      // print(value);
    });
  }
}
